﻿/* 版本记录
 * 0000 20200902  by linson add
 * 0001 
 * */

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Dao;
using GKQC.Common;
using SqlSugar;
using GKQC.DbHelper.Services;
using System.ComponentModel;
using System.Reflection;
using GKQC.Language;

namespace GKQC.Forms
{
    /// <summary>
    /// 系统管理主窗口
    /// </summary>
    public partial class FormUserRight : Form
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        //public UserModel currentUser = new UserModel();
        //List<UserModel> userList = null;
        List<UserRightModel> userRightList = null;
        FormStatus formStatus = FormStatus.Browser;
        EncryptSugar encryptSugar = null;
        //readonly string s0 = "123WER7890qwertyuiopasdfghjklzxcvbn123456789012er3";

        public FormUserRight(UserModel user, AllDbContext dbContext)
        {
            InitializeComponent();
            try
            {
                this.dataGridView1.AutoGenerateColumns = false;
                this.dataGridView2.AutoGenerateColumns = false;
                this.user = user;
                this.dbContext = dbContext;
                encryptSugar = EncryptSugar.GetInstance();


                BindingUsersOrGroups();
                //if(userList != null && userList.Count > 0)
                //    currentUser = userList[0];
                //else
                //    currentUser = new UserModel();

                BindingRights();
                this.dataGridView2.CellValueChanged += DataGridView2_CellValueChanged;
                SetControlsEnable();
                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message);
                Logger.LogError(ex);
            }
        }

        private void DataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (formStatus == FormStatus.Browser) return;
            try
            {
                if (dataGridView2.Columns[e.ColumnIndex].Name == "ColSelectAll")
                {
                    string value = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    UserRightModel model = dataGridView2.Rows[e.RowIndex].DataBoundItem as UserRightModel;
                    if (model != null)
                    {
                        model.Run = value;
                        model.Add = value;
                        model.Modi = value;
                        model.Delete = value;
                        model.Query = value;
                        model.Approve = value;
                        model.UnApprove = value;
                        model.Export = value;
                        dataGridView2.Refresh();
                    }
                }
            }catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void Fmain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }

        private void FormUser_Resize(object sender, EventArgs e)
        {

        }

        private void tsmAdd_Click(object sender, EventArgs e)
        {
        }

        void ClearControl()
        {
            //currentUser = new UserModel();
            dataGridView2.Rows.Clear();
        }


        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                //if (currentUser == null) return;

                this.Cursor = Cursors.WaitCursor;
                dataGridView2.EndEdit();

                List<UserRightModel> listAdd = new List<UserRightModel>();
                List<UserRightModel> listUpdate = new List<UserRightModel>();

                string code = string.Empty;
                string name = string.Empty;
                GetCurrentCode(out code, out name);

                foreach (UserRightModel ur in userRightList)
                {
                    if (rdoUser.Checked) ur.Type = "user";
                    else ur.Type = "usergroup";
                    ur.ModiUser = user.UserName;
                    ur.ModiDate = user.GetServerTime();
                    if (ur.Id <= 0)
                    {
                        ur.UserCode = code;
                        ur.UserName = name;
                        listAdd.Add(ur);
                    }
                    else
                        listUpdate.Add(ur);
                }

                if(listAdd.Count > 0) dbContext.QcDb.Insertable<UserRightModel>(listAdd).ExecuteCommand();
                if (listUpdate.Count > 0) dbContext.QcDb.Updateable<UserRightModel>(listUpdate).ExecuteCommand();

                formStatus = FormStatus.Browser;
                BindingRights();
                SetControlsEnable();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0003");
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }


        private void FormUser_Load(object sender, EventArgs e)
        {
            
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if(dataGridView1.CurrentRow == null)
            {
                QMessageBox.Show("請選擇要編輯的用戶!");
                return;
            }

            if (!UserRightService.CheckRight(this, this.user, RightType.Modi))
            {
                //QMessageBox.Show("權限不足!","提示");
                return;
            }
            formStatus = FormStatus.Edit;
            SetControlsEnable();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(dataGridView1.CurrentRow != null)
            {
                BindingRights();
                tsmExit.Enabled = true;
            }
            else
            {
                ClearControl();
                tsmExit.Enabled = false;
            }
        }

        void SetControlsEnable()
        {
            if(formStatus == FormStatus.Browser)
            {
                dataGridView1.Enabled = true;
                dataGridView2.ReadOnly = true;


                tsmAdd.Enabled = true;
                tsmEdit.Enabled = true;
                tsmDelete.Enabled = true;
                tsmSave.Enabled = false;
                tsmCancel.Enabled = false;
                tsmExit.Enabled = true;
                rdoUser.Enabled = true;
                rdoUserGroup.Enabled = true;
            }
            else
            {
                dataGridView1.Enabled = false;
                dataGridView2.ReadOnly = false;

                tsmAdd.Enabled = false;
                tsmEdit.Enabled = false;
                tsmDelete.Enabled = false;
                tsmSave.Enabled = true;
                tsmCancel.Enabled = true;
                tsmExit.Enabled = false;
                rdoUser.Enabled = false;
                rdoUserGroup.Enabled = false;
            }

            if (dataGridView1.CurrentRow == null) tsmEdit.Enabled = false;
            else tsmEdit.Enabled = true;
        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Browser;
            BindingRights();
            SetControlsEnable();
        }

        void BindingUsersOrGroups()
        {
            if (rdoUser.Checked)
            {
                var users = dbContext.QcDb.Queryable<UserModel>().Where(u => u.IsAdmin != true && u.IsUse)
                    .Select(f=>new
                    {
                        Code = f.UserCode,
                        Name = f.UserName
                    })
                    .ToList();
                dataGridView1.DataSource = users;
                //if (userList != null && userList.Count > 0)
                //    currentUser = userList[0];
                //else
                //    ClearControl();
            }
            else //if(rdo == rdoUserGroup)
            {
                var userGroups = dbContext.QcDb.Queryable<UserGroupModel>().Where(u => u.IsUse)
                                        .Select(f => new
                                        {
                                            Code = f.GroupCode,
                                            Name = f.GroupName
                                        })
                    .ToList();
                dataGridView1.DataSource = userGroups;
                //if (userList != null && userList.Count > 0)
                //    currentUser = userList[0];
                //else
                //    ClearControl();
            }
        }

        string sql = @"SELECT isnull(urm.[Id],0) AS [Id],isnull(urm.[UserCode],'') AS [UserCode],isnull(urm.[UserName],'') AS [UserName],rm.[FormCode] AS [FormCode],rm.[FormName] AS [FormName]
	,isnull(urm.[Run],rm.[Run]) AS [Run]
	,isnull(urm.[Add],rm.[Add]) AS [Add]
	,isnull(urm.[Modi],rm.[Modi]) AS [Modi]
	,isnull(urm.[Delete],rm.[Delete]) AS [Delete]
	,isnull(urm.[Query],rm.[Query]) AS [Query]
	,isnull(urm.[Export],rm.[Export]) AS [Export]
	,isnull(urm.[Approve],rm.[Approve]) AS [Approve]
	,isnull(urm.[UnApprove],rm.[UnApprove]) AS [UnApprove]
	,urm.[ModiUser] AS [ModiUser]
	,urm.[ModiDate] AS [ModiDate] 
    ,urm.[Type]
    ,rm.Sno
FROM [t_sys_right] rm 
left join  [t_sys_userright] urm 
ON ( [urm].[FormCode] = [rm].[FormCode] )  and   ( [urm].[UserCode] = @UserCode ) and ( [urm].[Type] = @Type ) 
";
        void BindingRights()
        {
            try
            {
                string code = string.Empty;
                string name = string.Empty;
                GetCurrentCode(out code, out name);
                if (!string.IsNullOrWhiteSpace(code))
                {
                    if (rdoUser.Checked)
                    {
                            userRightList = dbContext.QcDb.SqlQueryable<UserRightModel>(sql)
                                .AddParameters(new { UserCode = code })
                                .AddParameters(new { Type = "user" })
                                .OrderBy(t=>t.Sno, OrderByType.Asc)
                                .ToList();
                    }
                    else //if(rdo == rdoUserGroup)
                    {

                        userRightList = dbContext.QcDb.SqlQueryable<UserRightModel>(sql)
                            .AddParameters(new { UserCode = code })
                            .AddParameters(new { Type = "usergroup" })
                            .ToList();
                    }
                }

                if (userRightList == null) userRightList = new List<UserRightModel>();
                dataGridView2.DataSource = new BindingList<UserRightModel>(userRightList);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message ,"異常S0006");
            }
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dataGridView2.Columns[e.ColumnIndex] == ColFormCode || dataGridView2.Columns[e.ColumnIndex] == ColFormName)
            {
                e.Cancel = true;
                return;
            }
        }

        private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void rdoUser_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                RadioButton rdo = sender as RadioButton;
                if (rdo == null) return;
                if (!rdo.Checked) return;
                BindingUsersOrGroups();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        void GetCurrentCode(out string code,out string name)
        {
            code = name = string.Empty;
            try
            {
                if (dataGridView1.CurrentRow != null)
                {
                    var r = dataGridView1.CurrentRow.DataBoundItem;
                    if (r != null)
                    {
                        PropertyInfo p = r.GetType().GetProperty("Code");
                        if (p != null) code = p.GetValue(r, null).ToString();

                        p = r.GetType().GetProperty("Name");
                        if (p != null) name = p.GetValue(r, null).ToString();
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                BindingRights();
                tsmEdit.Enabled = true;
            }
            else
            {
                ClearControl();
                tsmEdit.Enabled = false;
            }
        }
    }
}
